package com.eboss2.sbs.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.TransChannelAdapter;
import com.eboss2.sbs.consts.Constant;
import com.eboss2.sbs.consts.ErrorAction;
import com.eboss2.sbs.database.dao.TransDataDao;
import com.eboss2.sbs.model.TransDataBean;
import com.eboss2.sbs.util.RxBus;
import com.eboss2.sbs.weight.helper.ItemDragHelperCallback;

import java.util.List;
import java.util.Observer;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Meiji on 2017/3/10.
 */

public class TransChannelActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private TransChannelAdapter adapter;
    private TransDataDao dao = new TransDataDao();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trans_channel);
        initView();
        initData();
    }

    @Override
    protected void onStop() {
        super.onStop();
        onSaveData();
    }

    private void initView() {
        RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
        relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
        showView(R.id.titleback_btn_back, true);
        setTvText(R.id.tv_title, "我的交易数据");
        findViewById(R.id.titleback_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                finish();
            }
        });

        recyclerView = findViewById(R.id.recycler_view);
    }

    private void initData() {
        final List<TransDataBean> enableItems = dao.query(Constant.NEWS_CHANNEL_ENABLE);
        final List<TransDataBean> disableItems = dao.query(Constant.NEWS_CHANNEL_DISABLE);

        GridLayoutManager manager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(manager);

        ItemDragHelperCallback callback = new ItemDragHelperCallback();
        final ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);

        adapter = new TransChannelAdapter(this, helper, enableItems, disableItems);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int viewType = adapter.getItemViewType(position);
                return viewType == TransChannelAdapter.TYPE_MY || viewType == TransChannelAdapter.TYPE_OTHER ? 1 : 3;
            }
        });
        recyclerView.setAdapter(adapter);
        adapter.setOnMyChannelItemClickListener(new TransChannelAdapter.OnMyChannelItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
//                Toast.makeText(TransChannelActivity.this, enableItems.get(position).getChannelName() + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onSaveData() {

        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                List<TransDataBean> oldItems = dao.query(Constant.NEWS_CHANNEL_ENABLE);
                emitter.onNext(!compare(oldItems, adapter.getmMyChannelItems()));
            }
        }).subscribeOn(Schedulers.io())
        .doOnNext(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    List<TransDataBean> enableItems = adapter.getmMyChannelItems();
                    List<TransDataBean> disableItems = adapter.getmOtherChannelItems();
                    dao.removeAll();
                    for (int i = 0; i < enableItems.size(); i++) {
                        TransDataBean bean = enableItems.get(i);
                        dao.add(bean.getChannelId(), bean.getChannelName(), bean.getValue(), bean.getType(),Constant.NEWS_CHANNEL_ENABLE, i);
                    }
                    for (int i = 0; i < disableItems.size(); i++) {
                        TransDataBean bean = disableItems.get(i);
                        dao.add(bean.getChannelId(), bean.getChannelName(), bean.getValue(), bean.getType(), Constant.NEWS_CHANNEL_DISABLE, i);
                    }
                }
            }
        })
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                RxBus.getInstance().post(FirstActivity.TAG, aBoolean);
            }
        }, ErrorAction.error());
    }

    public synchronized <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size())
            return false;
//        Collections.sort(a);
//        Collections.sort(b);
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }
}




